package com.thoughtworks.opensource.yui.dd.client.windowresources;

/*
   Copyright 2006 C. K. Sidu Ponnappa

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

import com.thoughtworks.opensource.yui.dd.client.Listener;
import com.thoughtworks.opensource.yui.dd.client.events.Event;
import com.thoughtworks.opensource.yui.dd.client.events.EventType;
import com.thoughtworks.opensource.yui.dd.client.exceptions.EventNotRegisteredException;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;

/**
 * Created by IntelliJ IDEA.
 * Author: C. K. Sidu Ponnappa
 * Date: Dec 16, 2006
 * Time: 12:28:38 AM
 * ThoughtWorks India Pvt. Ltd.
 */
public class EventRegistry {
    protected HashMap registry = new HashMap();

    public void registerListenerFor(Listener listener, EventType eventType) {
        if (alreadyRegistered(eventType)) {
            getSetOfListeners(eventType).add(listener);
        } else {
            HashSet listeners = new HashSet();
            listeners.add(listener);
            registry.put(eventType, listeners);
        }
    }

    protected boolean alreadyRegistered(EventType eventType) {
        return registry.keySet().contains(eventType);
    }

    public void notifyListenersFor(EventType eventType, Object source, Object payload) {
        HashSet listeners = getSetOfListeners(eventType);
        Event event = new Event(eventType, source, payload);
        Iterator iterator = listeners.iterator();
        while (iterator.hasNext()) {
            ((Listener) iterator.next()).notify(event);
        }
    }

    private HashSet getSetOfListeners(EventType eventType) {
        HashSet listeners = ((HashSet) registry.get(eventType));
        if (listeners == null) throw new EventNotRegisteredException();
        return listeners;
    }
}
